<?php
/*------------------------------------------------------ */
//-- 提成处理
//-- Author: iqgmy
/*------------------------------------------------------ */

namespace distribution\base;

use app\BaseModel;
use app\jxcshop\model\JiaquanfenhongJc;
use app\member\model\UsersLevelApplyModel;
use think\Db;
use app\AdminController;
use app\member\model\AccountModel;
use app\member\model\UsersBindSuperiorModel;
use app\member\model\{UsersModel, UsersLevelModel};
use app\jxcshop\model\{OrderModel, OrderGoodsModel, GoodsModel};
use app\distribution\model\{DividendAwardModel, DividendRoleModel};
use think\facade\Cache;
use app\mainadmin\model\SmsTplModel;

class Dividendjxc extends BaseModel
{
    public $UsersModel;

    public function __construct($Model)
    {
        parent::__construct();
        $this->UsersModel = new UsersModel();
        $this->Model = $Model;
    }

    /*------------------------------------------------------ */
    //-- 计算提成并记录或更新
    //-- $orderInfo array 订单数据
    //-- $type string 操作类型
    //-- $status int 分佣状态，操作类型为add时，根据传值设置默认状看你 关闭态
    //-- return bool 如果$type为add或订单为身份订单则返回数组
    /*------------------------------------------------------ */
    public function _eval(&$orderInfo, $type = '', $status = 0)
    {



        //身份订单处理
        //if ($orderInfo['is_split'] > 0) return true;//需要拆单的不执行
        $upData = [];//更新分佣记录状态
        $OrderModel = new OrderModel();
        $order_operating = '';
        $send_msg = false;
        //先计算佣金

        //检测 如果购买代理升级商品的上级是会员 就将该用户移到会员上级代理



        //
        if ($type == 'pay') {//订单支付成功

            $isLook = redisLook('fr_jxcshop_order_has_pay_' . $orderInfo['order_id'], 20);
            if ($isLook == true) {
                $goodsList = (new OrderGoodsModel)->where('order_id', $orderInfo['order_id'])->select()->toArray();
                $goodsnames = '';
                $goodids = 0;
                $jiangchiamount = 0;
                foreach ($goodsList as $k => $goods) {
                    //增加奖金池金额
                    $_goods = Db::table("shop_goods_jxc")->where('goods_id', $goods['goods_id'])->find();
                    if (!empty($_goods['jiangjinchi'])) {

                        $goodsnames .=  $goods['goods_name'];
                        $goodids .= $goods['goods_id'].' | ';
                        $jiangchiamount += $_goods['jiangjinchi'];
                        //$jc->total_amount = $jc->total_amount + $amount;
                        //$jcRes = $jc->save();



                    }
                    //end
                    $goodsList[$k]['send_bl'] = $_goods['send_bl'];
                }



                $data = [
                    'jc_id' => 1,
                    'goods_id' => $goodids,//$goods['goods_id'],
                    'order_id' => $orderInfo['order_id'],
                    'order_sn' => $orderInfo['order_sn'],
                    'goods_name' => $goodsnames,//$goods['goods_name'],
                    'amount' => $orderInfo['order_amount'],
                    'enter_amount' => $jiangchiamount,//$_goods['jiangjinchi'],
                    'createtime' => time(),
                    'stage' => date('Ym'),
                    'isstatus' => 0,
                ];
                if($jiangchiamount>0){
                    $result = (new JiaquanfenhongJc())->insert($data);
                }



                //if ($res == false) return false;
                $upData['status'] = $OrderModel->config['DD_PAYED'];
                $send_msg = true;
                $this->assemblyPay($orderInfo);


                return true;
            }
            return false;

        } elseif ($type == 'cancel') {//订单取消
            $order_operating = '订单取消';
            $send_msg = true;
            $this->assemblyPay($orderInfo, 3);

        } elseif ($type == 'unpayed') {//未付款
            if ($orderInfo['order_status'] == $OrderModel->config['OS_CANCELED']) {
                $upData['status'] = $OrderModel->config['DD_CANCELED'];
            } elseif ($orderInfo['order_status'] == $OrderModel->config['OS_RETURNED']) {
                $upData['status'] = $OrderModel->config['DD_RETURNED'];
            } else {
                $upData['status'] = $OrderModel->config['DD_UNCONFIRMED'];
            }
            $this->assemblyPay($orderInfo, 2);
        } elseif ($type == 'shipping') {//发货
            $upData['status'] = $OrderModel->config['DD_SHIPPED'];
        } elseif ($type == 'unshipping') {//未发货
            $this->assemblyPay($orderInfo, 5);
            $upData['status'] = $OrderModel->config['DD_PAYED'];
        } elseif ($type == 'sign') {//签收
            $upData['status'] = $OrderModel->config['DD_SIGN'];
            $this->assemblySign($orderInfo);
        } elseif ($type == 'unsign') {//撤销签收
            $this->assemblyPay($orderInfo, 5);
            return $this->Model->returnArrival($orderInfo['order_id'], 'unsign', $orderInfo['user_id']);
        } elseif ($type == 'returned') {//退货
            return $this->Model->returnArrival($orderInfo['order_id'], 'returned', $orderInfo['user_id']);
        }

        if ($send_msg == true) {
            $this->Model->sendMsg($type, $orderInfo['order_id'], $order_operating);//发送模板消息
        }

        if ($type == 'sign' && $orderInfo['order_type'] == 0) {//签收,执行佣金到帐
            $shop_after_sale_limit = settings('shop_after_sale_limit');
            if ($shop_after_sale_limit == 0) {
                //return $this->Model->evalArrival($orderInfo['order_id'], 'order');
            }
        } elseif ($type == 'pay') {
            //return $this->Model->evalArrival($orderInfo['order_id'], 'order');

        }

        return true;
    }

    /**
     * [assemblySign  自定义交易组件同步订单签收]
     * @param array $orderInfo [订单信息]
     */
    public function assemblySign($orderInfo = [])
    {
        $WeixinVideoOrderModel = new \app\weixin\model\WeixinVideoOrderModel();
        $assemblyInfo = $WeixinVideoOrderModel->where('out_order_id', $orderInfo['order_id'])->find();
        if (empty($assemblyInfo) == false) {
            $assemblyInfo = $assemblyInfo->toArray();
            $param = [];
            $param['order_id'] = $assemblyInfo['order_id'];
            $param['out_order_id'] = $assemblyInfo['out_order_id'];
            $param['openid'] = $assemblyInfo['openid'];
            $res = $WeixinVideoOrderModel->signOrder($param);
        }
        return true;
    }

    /**
     * [assemblyPay 自定义交易组件同步订单状态]
     * @param array $orderInfo [订单信息]
     * @param integer $status [订单状态，1:支付成功,2:支付失败,3:用户取消,4:超时未支付;5:商家取消;10:其他原因取消]
     */
    public function assemblyPay($orderInfo = [], $status = 1)
    {
        $WeixinVideoOrderModel = new \app\weixin\model\WeixinVideoOrderModel();
        $assemblyInfo = $WeixinVideoOrderModel->where('out_order_id', $orderInfo['order_id'])->find();
        if (empty($assemblyInfo) == false) {
            $assemblyInfo = $assemblyInfo->toArray();
            $WeixinVideoOrderModel->updateOrderStatus($assemblyInfo, $status, $orderInfo['transaction_id']);
        }
        return true;
    }

    /**
     * [assemblyAddOrder 自定义交易组件提交订单]
     * @param array $orderInfo [订单信息]
     * @param array $goodsList [购买商品]
     */
    public function assemblyAddOrder($orderInfo = [], $goodsList = [])
    {
        $WeixinVideoGoodsModel = new \app\weixin\model\WeixinVideoGoodsModel();
        $product_infos = [];
        $i = 0;
        foreach ($goodsList as $goods) {
            $vgoods = $WeixinVideoGoodsModel->where('out_product_id', $goods['goods_id'])->find();
            if (empty($vgoods) == false) {
                $product_infos[$i]['out_product_id'] = $goods['goods_id'];
                $product_infos[$i]['out_sku_id'] = $goods['sku_id'];
                $product_infos[$i]['product_cnt'] = $goods['goods_number'];
                $product_infos[$i]['sale_price'] = $goods['sale_price'];
                $product_infos[$i]['path'] = "pages/jxcshop/goods/info?goods_id=" . $goods['goods_id'];
                $product_infos[$i]['title'] = $goods['goods_name'];
                $product_infos[$i]['head_img'] = config('config.host_path') . $goods['goods_img'];
                $i++;
            }
        }
        if (empty($product_infos) == false) {
            $scene = input('scene');
            $times = date('Y-m-d H:i:s', time());
            $data = [];
            $data['create_time'] = $times;
            $data['type'] = 0;
            $data['out_order_id'] = $orderInfo['order_id'];
            $data['path'] = "pages/jxcshop/order/info?order_id=" . $orderInfo['order_id'];


            $data['openid'] = (new \app\weixin\model\WeiXinUsersModel)->where('user_id', $orderInfo['user_id'])->value('wx_openid');
            $data['out_user_id'] = $orderInfo['user_id'];
            $data['scene'] = $scene;
            $data['order_detail'] = [];
            $data['order_detail']['product_infos'] = $product_infos;
            $data['order_detail']['pay_info']['pay_method'] = '微信支付';
            $data['order_detail']['pay_info']['prepay_id'] = 000000;
            $data['order_detail']['pay_info']['prepay_time'] = $times;
            $data['order_detail']['pay_info']['pay_method_type'] = 0;
            $data['order_detail']['price_info']['order_price'] = $orderInfo['order_amount'] * 100;
            $data['order_detail']['price_info']['freight'] = $orderInfo['shipping_fee'] * 100;
            $data['order_detail']['price_info']['discounted_price'] = ($orderInfo['diy_discount'] + $orderInfo['use_bonus'] + $orderInfo['discount']) * 100;
            $data['order_detail']['price_info']['additional_price'] = 0;
            $data['order_detail']['price_info']['additional_remarks'] = '';
            $data['delivery_detail']['delivery_type'] = 1;
            $data['address_info']['receiver_name'] = $orderInfo['consignee'];
            $data['address_info']['detailed_address'] = $orderInfo['address'];
            $data['address_info']['tel_number'] = $orderInfo['mobile'];

            $merger_name = explode(',', $orderInfo['merger_name']);
            $data['address_info']['country'] = $merger_name[0];
            $data['address_info']['province'] = $merger_name[1];
            $data['address_info']['city'] = $merger_name[2];
            $data['address_info']['town'] = '';

            $WeixinVideoOrderModel = new \app\weixin\model\WeixinVideoOrderModel();

            $res = $WeixinVideoOrderModel->addOrder($data);
            if ($res['errcode'] <= 0) {
                $data['package'] = json_encode($res['data'], JSON_UNESCAPED_UNICODE);
                $data['order_detail'] = json_encode($data['order_detail'], JSON_UNESCAPED_UNICODE);
                $data['delivery_detail'] = json_encode($data['delivery_detail'], JSON_UNESCAPED_UNICODE);
                $data['address_info'] = json_encode($data['address_info'], JSON_UNESCAPED_UNICODE);
                $data['order_id'] = $res['data']['order_id'];
                $data['ticket'] = $res['data']['ticket'];
                $data['ticket_expire_time'] = $res['data']['ticket_expire_time'];
                $data['final_price'] = $res['data']['final_price'];
                $data['add_time'] = time();
                $WeixinVideoOrderModel->save($data);
            }
        }
        return true;
    }


    /**
     * 获取所属上级 getProfit
     * @param int $pid [上级id]
     * @return void
     */
    public function getProfit($pid = 0)
    {
        $profituser = Db::table("users")->where('user_id', $pid)->field('role_id,profit_pid,user_id')->find();
        if ($profituser['role_id'] <= 1) {
            if ($profituser['profit_pid'] == 0) {
                return 0;
            }
            return $this->getProfit($profituser['profit_pid']);
        }
        return $profituser['user_id'];
    }
    /*------------------------------------------------------ */
    //-- 计算提成并记录或更新
    /*------------------------------------------------------ */
    public function saveLog(&$orderInfo, &$goodsList, $status = 0)
    {
        //平级奖设置
        $settings = settings();
        $pingjimoney = $settings['pingjimoney'] ? $settings['pingjimoney'] : 0;

        $returnArr['dividend_amount'] = 0;
        $nowLevel = 0;//当前处理级别
        $buyUserInfo = $this->UsersModel->info($orderInfo['user_id']);//获取购买会员信息
        //参与分佣商品处理
        $dividend_goods = [];//所有分佣商品
        $dividend_goods_total = 0;//所有分佣商品金额
        foreach ($goodsList as $k => $goods) {
            $_goods = GoodsModel::where('goods_id', $goods['goods_id'])->field('award_value,send_bl,is_dividend,region_award_value,goods_type,membermoney,dailimoney,jinlimoney')->find()->toArray();

            $goodsList[$k]['send_bl'] = $_goods['send_bl'];
            if ($_goods['is_dividend'] == 1) {
                $diy_discount = 0;


                $goods['goods_type'] = $_goods['goods_type'];
                $goods['membermoney'] = $_goods['membermoney'];
                $goods['dailimoney'] = $_goods['dailimoney'];
                $goods['jinlimoney'] = $_goods['jinlimoney'];
                $goods['award_value'] = json_decode($_goods['award_value'], true);
                $goods['region_award_value'] = json_decode($_goods['region_award_value'], true);
                $goods['goods_total'] = priceFormat($goods['sale_price']  - $goods['usd_bonus_price'] - $diy_discount);//商品总价小计
                $dividend_goods_total += $goods['goods_total'];
                $dividend_goods[$goods['goods_id'] . '_' . $goods['sku_id']] = $goods;
            }
        } //
        $parentId = $buyUserInfo['profit_pid'];
        $UsersLevelModel = new \app\member\model\UsersLevelModel();
        $UsersLevelAgentModel = new \app\member\model\UsersLevelAgentModel();
        $levelList = $UsersLevelModel->getRows();
        // $diff_region = [];// 已分配出去的区域奖
        if ($orderInfo['order_type'] !== 5) {

            if ($orderInfo['order_status'] < 1) {
                return $returnArr;
            }

            foreach ($levelList as $level) { // 区域奖
                $where = [];
                $where[] = ['province', '=', $orderInfo['province']];
                if ($level['identification'] == 'city_agent') {
                    $where[] = ['city', '=', $orderInfo['city']];
                }
                if ($level['identification'] == 'district_agent') {
                    $where[] = ['city', '=', $orderInfo['city']];
                    $where[] = ['district', '=', $orderInfo['district']];
                }
                if ($level['identification'] == 'street_agent') {
                    $where[] = ['city', '=', $orderInfo['city']];
                    $where[] = ['district', '=', $orderInfo['district']];
                    $where[] = ['street', '=', $orderInfo['street']];
                }


                $where[] = ['level_id', '=', $level['level_id']];
                $agentInfo = $UsersLevelAgentModel->where($where)->find();
                unset($where);
                $dividend_amount_region = 0;
                if (empty($agentInfo) == false) {
                    foreach ($dividend_goods as $gk => $goods) {
                        $num = $goods['region_award_value'][$level['level_id']]['num'];  //


                    }

                    if ($dividend_amount_region > 0) {
                        $returnArr['dividend_amount'] += $dividend_amount_region;
                        $agentUser = $this->UsersModel->info($agentInfo['user_id']);
                        $res = $this->createLog($orderInfo, $agentUser, $dividend_amount_region, $level['level_name'] . '区域奖', '用户【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $dividend_amount_region . '元' . $level['level_name'] . '区域代理奖励', $dividend_goods_total, 'none');
                        if ($res !== true) return false;
                    }
                }
            }
        }

        if ($orderInfo['order_type'] == 4) { //
            if ($orderInfo['order_status'] < 1) {
                return $returnArr;
            }

            if ($parentId < 1) return $returnArr;//没有上级不执行
            $userInfo = $this->UsersModel->info($parentId); //获取会员信息  $parentId为上级用户ID
            $dividend_amount = 0;
            $see_dividend_amount = 0;
            $same_dividend_amount = 0;
            $sameUserId = 0;
            $profitUser = [];
            // 见点收益会员
            if ($userInfo['role_id'] == 2) {
                $sameUserId = $userInfo['pid'];
            } else {
                $profitUser = $this->UsersModel->info($userInfo['profit_pid']);
                if ($profitUser['role_id'] < 2) {
                    $profitUid = $profitUser['pid'];
                    do {
                        $profitUser = $this->UsersModel->info($profitUid);
                        $profitUid = $profitUser['pid'];
                        if ($profitUser['role_id'] == 2) break;
                    } while ($profitUid > 0);
                }

                $sameUserId = $profitUser['pid']; // 见点收益会员
            }
            // 平级奖用户
            $sameUser = [];
            if ($sameUserId > 0) {
                /*
                do {
                    $sameUser = $this->UsersModel->info($sameUserId);
                    $sameUserId = $sameUser['pid'];
                    if ($sameUser['role_id'] == 2) break;
                } while ($sameUserId > 0);
                */
                //判断购买者如果是经理就直接给平级奖
                //if($buyUserInfo['role_id'] == 2 || $buyUserInfo['role_id'] == 1){
                //   do {
                //      $sameUser = $this->UsersModel->info($sameUserId);
                //      $sameUserId = $sameUser['pid'];

                //       if ($sameUser['role_id'] == 2) break;
                //   } while ($sameUserId > 0);
                //}else{
                //如果购买者不是经理则排除上级的第一个是经理不给平级奖

                $where[] = ['pid', '=', $sameUserId];
                $samesjUser = Db::table('users')->where($where)->find();

                if($samesjUser['role_id'] != 2){
                do {
                    $sameUser = $this->UsersModel->info($sameUserId);
                    $sameUserId = $sameUser['pid'];

                    if ($sameUser['role_id'] == 2) break;
                } while ($sameUserId > 0);
                }




            }
            foreach ($dividend_goods as $k => $goods) {
                $boss_dividend_amount = 0; // 老板收益
                if ($goods['goods_type'] !== 4) {
                    continue;
                }

                if (empty($goods['award_value'][$userInfo['role_id']]) == false) { // 直推奖
                    $val = $goods['award_value'][$userInfo['role_id']];
                    if (empty($val['num']) == false && !is_array($val['num'])) {
                        $dividend_amount += $val['num'] ;
                        $boss_dividend_amount = $val['num'] ;
                    }
                };
                //if ($userInfo['role_id'] < 2 && empty($profitUser) == false) { // 见点奖

                if($buyUserInfo['profit_pid'] > 0){
                    $profit_pid = $this->getProfit($buyUserInfo['profit_pid']);
                    $jiangdianUser = $this->UsersModel->info($profit_pid);  //琳凯

                    if($jiangdianUser['pid'] > 0){
                        $pinjiUser = $this->UsersModel->info($jiangdianUser['pid']);
                        $pinjiUser_id = $pinjiUser['user_id'];
                    }

                }

                if ($buyUserInfo['profit_pid'] > 0) { // 见点奖

                    $val = $goods['award_value'][$profitUser['role_id']];
                    if (empty($val['see_num']) == false) {
                        $boss_dividend_amount = $val['see_num'] ;
                        $see_dividend_amount += $boss_dividend_amount;
                    }

                }

                if ($boss_dividend_amount > 0 && empty($pinjiUser) == false) { // 平级奖
                    $val = $goods['award_value'][$pinjiUser['role_id']];
                    if (empty($val['same_num']) == false) {
                        $same_dividend_amount += bcdiv($boss_dividend_amount * $val['same_num'], 100, 2);
                        //$same_dividend_amount += bcdiv($boss_dividend_amount * $val['same_num'], 100, 2);
                    }
                }
            }
            //            $status = 'none';
            if ($dividend_amount > 0) {
                $returnArr['dividend_amount'] += $dividend_amount;
                $md5Log = strtolower(md5($orderInfo['order_sn'] . '_' . $userInfo['user_id'] . '_直推奖_' . $buyUserInfo['user_id']));
                $res = $this->createLog($orderInfo, $userInfo, $dividend_amount, '直推奖', '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买加盟区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' .
                    $dividend_amount . '元直推奖励', $dividend_goods_total, $status, 0, $md5Log);
               if ($res == false) return false;
            }

            if ($see_dividend_amount > 0) {
                $returnArr['dividend_amount'] += $see_dividend_amount;
                $md5Log = strtolower(md5($orderInfo['order_sn'].'_'.$jiangdianUser['user_id'].'见点奖'.$buyUserInfo['user_id']));
                $res = $this->createLog($orderInfo, $jiangdianUser, $see_dividend_amount, '见点奖', '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买加盟区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $see_dividend_amount . '元见点奖励', $dividend_goods_total, $status,0,$md5Log);
                if ($res == false) return false;
            }

            //获取当前用户的所有父级经理、代理
            $pingjisUser = $this->UsersModel->info($jiangdianUser['pid']);
            if($pinjiUser['role_id'] == 2 && $pinjiUser_id > 0){

                if ($same_dividend_amount > 0 && $pinjiUser['role_id'] == 2 && $pinjiUser_id > 0) {
                    $returnArr['dividend_amount'] += $same_dividend_amount;
                    $md5Log = strtolower(md5($orderInfo['order_sn'].'_'.$pinjiUser['user_id'].'平级奖_'.$buyUserInfo['user_id']));
                    $res = $this->createLog($orderInfo, $pinjiUser, $same_dividend_amount, '平级奖', '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买加盟区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $same_dividend_amount . '元平级奖励', $dividend_goods_total, $status,0,$md5Log);
                    if ($res == false) return false;
                }

            }else if($pingjisUser['role_id'] == 2 && $pinjiUser['role_id'] != 2){
                if($boss_dividend_amount > 0){
                    $val = $goods['award_value'][$pingjisUser['role_id']];
                    $same_dividend_amount += bcdiv($boss_dividend_amount * $val['same_num'], 100, 2);
                }
                $pinjiUser = $pingjisUser;
                $pinjiUser_id = $pingjisUser['user_id'];

                if ($same_dividend_amount > 0 && $pinjiUser['role_id'] == 2 && $pinjiUser_id > 0) {
                    $returnArr['dividend_amount'] += $same_dividend_amount;
                    $md5Log = strtolower(md5($orderInfo['order_sn'].'_'.$pinjiUser['user_id'].'平级奖_'.$buyUserInfo['user_id']));
                    $res = $this->createLog($orderInfo, $pinjiUser, $same_dividend_amount, '平级奖', '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买加盟区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $same_dividend_amount . '元平级奖励', $dividend_goods_total, $status,0,$md5Log);
                    if ($res == false) return false;
                }

            }else if($pingjissuser['role_id'] == 2 && $pingjisUser['role_id'] != 2 && $pinjiUser['role_id'] != 2){
                if($boss_dividend_amount > 0){
                    $val = $goods['award_value'][$pingjissuser['role_id']];
                    $same_dividend_amount += bcdiv($boss_dividend_amount * $val['same_num'], 100, 2);
                }
                $pinjiUser = $pingjissuser;


            }


        }

        if ($orderInfo['order_type'] == 0 || $orderInfo['order_type'] == 6) {

            if ($orderInfo['order_status'] < 1) {
                return $returnArr;
            }

            $dividend_amount_daili = 0;     //代理总金额
            $dividend_amount_jingli = 0;    //经理总金额
            $dividend_amount_jicha = 0;     //级差总金额

            //
            foreach ($dividend_goods as $goods) {
                if (empty($goods['award_value'])) continue;
                $award = [];
                foreach ($goods['award_value'] as $value) {
                    if ($value['buyId'] == $buyUserInfo['role_id']) {
                        $award = $value;
                        break;
                    }
                }
                $dailiRate = $award['daili'] ?? 0;
                $jingliRate = $award['jingli'] ?? 0;
                $jichaRate = ($jingliRate - $dailiRate) > 0 ? ($jingliRate - $dailiRate) : 0;

                //
                $dividend_amount_daili += bcdiv($goods['sale_price'] * $dailiRate , 100, 2);
                //经理分销总金额（首个）
                $dividend_amount_jingli += bcdiv($goods['sale_price'] * $jingliRate , 100, 2);
                //计算级差总金额
                $dividend_amount_jicha += bcdiv($goods['sale_price'] * $jichaRate , 100, 2);
            }

            //
            $buyUserParents = $this->getParentsByUserId($buyUserInfo['user_id']);
            if (empty($buyUserParents)) {
                return $returnArr;
            }

            foreach ($buyUserParents as $index => $buyUserParent) {
                if ($index == 0) {
                    //级别
                    if ($buyUserParent['role_id'] == 1 && $dividend_amount_daili > 0) {
                        $returnArr['dividend_amount'] += $dividend_amount_daili;
                        $res = $this->createLog($orderInfo, $buyUserParent, $dividend_amount_daili, '分销奖', '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买普通区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $dividend_amount_daili . '元' . ($index) . '级奖励', $dividend_goods_total, $status);
                        //if (!$res) return false;


                        $buyUserParentFirst = $buyUserParents[$index + 1] ?? [];
                        if (!empty($buyUserParentFirst) && $dividend_amount_jicha > 0) {
                            //级别
                            if($buyUserParentFirst['role_id'] == 1) {
                                for ($i = 2; $i < count($buyUserParents); $i++) {
                                    $topBuyUserParent = $buyUserParents[$i] ?? [];
                                    if (!empty($topBuyUserParent) && $topBuyUserParent['role_id'] == 2) { //
                                        $returnArr['dividend_amount'] += $dividend_amount_jicha;
                                        $this->createLog($orderInfo, $topBuyUserParent, $dividend_amount_jicha, '级差奖', '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买普通区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $dividend_amount_jicha . '元' . ($index + 1) . '级奖励', $dividend_goods_total, $status);

                                            //
                                            $topBuyUserParentSecond = $buyUserParents[$i + 1] ?? [];
                                            if (!empty($topBuyUserParentSecond) && $topBuyUserParentSecond['role_id'] == 2) {
                                                $dividend_amount_pingji = bcdiv($dividend_amount_jicha * $pingjimoney, 100, 2); //平级奖是固定的10%
                                                $returnArr['dividend_amount'] += $dividend_amount_pingji;
                                                $this->createLog($orderInfo, $topBuyUserParentSecond, $dividend_amount_pingji, '平级奖', '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买普通区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $dividend_amount_pingji . '元' . ($index + 2) . '级奖励', $dividend_goods_total, $status);
                                            }

                                            break;
                                    }
                                }
                            }

                            //级别
                            if ($buyUserParentFirst['role_id'] == 2) {
                                $returnArr['dividend_amount'] += $dividend_amount_jicha;
                                $res = $this->createLog($orderInfo, $buyUserParentFirst, $dividend_amount_jicha, '级差奖', '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买普通区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $dividend_amount_jicha . '元' . ($index + 1) . '级奖励', $dividend_goods_total, $status);
                                //if (!$res) return false;

                                //级别
                                $buyUserParentSecond = $buyUserParents[$index + 2] ?? [];
                                if (!empty($buyUserParentSecond) && $dividend_amount_jicha > 0) {
                                    $dividend_amount_pingji = bcdiv($dividend_amount_jicha * $pingjimoney, 100, 2); //平级奖是固定的10%
                                    $returnArr['dividend_amount'] += $dividend_amount_pingji;
                                    $res = $this->createLog($orderInfo, $buyUserParentSecond, $dividend_amount_pingji, '平级奖', '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买普通区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $dividend_amount_pingji . '元' . ($index + 2) . '级奖励', $dividend_goods_total, $status);
                                    //if (!$res) return false;
                                }
                            }

                        }


                    }


                    //级别
                    if ($buyUserParent['role_id'] == 2 && $dividend_amount_jingli > 0) {
                        $returnArr['dividend_amount'] += $dividend_amount_jingli;
                        $res = $this->createLog($orderInfo, $buyUserParent, $dividend_amount_jingli, '分销奖', '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买普通区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $dividend_amount_jingli . '元' . ($index) . '级奖励', $dividend_goods_total, $status);
                        //if (!$res) return false;

                        //级别
                        $buyUserParentFirst = $buyUserParents[$index + 1] ?? [];
                        if (!empty($buyUserParentFirst)) {
                            $dividend_amount_pingji = bcdiv($dividend_amount_jingli * $pingjimoney, 100, 2); //平级奖是固定的10%
                            $returnArr['dividend_amount'] += $dividend_amount_pingji;
                            $res = $this->createLog($orderInfo, $buyUserParentFirst, $dividend_amount_pingji, '平级奖', '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买普通区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $dividend_amount_pingji . '元' . ($index + 1) . '级奖励', $dividend_goods_total, $status);
                            //if (!$res) return false;
                        }
                    }
                }
            }


        }

        if ($orderInfo['order_type'] == 6 && $buyUserInfo['role_id']  == 0) {

            if ($orderInfo['order_status'] < 1) {
                return $returnArr;
            }

            $dividend_amount_daili = 0;     //代理总金额
            $dividend_amount_jingli = 0;    //经理总金额
            $dividend_amount_jicha = 0;     //级差总金额
            $member_amount_member = 0;     // 会员购物分

            //抽取当前用户等级分销率
            foreach ($dividend_goods as $goods) {

                $changedata['integral_money'] += $goods['membermoney']*$goods['goods_number'];

                $dailiRate = $goods['dailimoney'] > 0 ? $goods['dailimoney'] : 0;  //代理奖励比例
                $jingliRate = $goods['jinlimoney'] > 0 ? $goods['jinlimoney'] : 0;  //经理奖励比例
                $jichaRate = ($jingliRate - $dailiRate) > 0 ? ($jingliRate - $dailiRate) : 0;

                //会员推荐会
                $member_amount_member += $goods['membermoney'] ;

                //代理分销总金额（首个）
                $dividend_amount_daili += bcdiv($goods['sale_price'] * $dailiRate , 100, 2);
                //经理分销总金额（首个）
                $dividend_amount_jingli += bcdiv($goods['sale_price'] * $jingliRate , 100, 2);
                //计算级差总金额
                $dividend_amount_jicha += bcdiv($goods['sale_price'] * $jichaRate , 100, 2);
            }



            //获取当前用户的所有父级经理、代理
            $buyUserParents = $this->getParentsByUserId($buyUserInfo['user_id']);
            if (empty($buyUserParents)) {
                return $returnArr;
            }
            /*
            echo '代理：'.$dividend_amount_daili;
            echo '<br>';

            echo '经理：'.$dividend_amount_jingli;
            echo '<br>';
            echo  '极差：'.$dividend_amount_jicha;
            echo '<br>';
            dump($member_amount_member);exit;
            */

            foreach ($buyUserParents as $index => $buyUserParent) {
                if ($index == 0) {
                    //级别
                    if ($buyUserParent['role_id'] == 3) {



                        $inArr['dividend_amount'] = $member_amount_member;
                        $inArr['dividend_bean'] = 0.00;
                        $inArr['order_type'] = 'order';
                        $inArr['status'] = 9;
                        $inArr['order_id'] = $orderInfo['order_id'];
                        $inArr['order_sn'] = $orderInfo['order_sn'];
                        $inArr['buy_uid'] = $orderInfo['user_id'];
                        $inArr['order_amount'] = $orderInfo['order_amount'];
                        $inArr['dividend_uid'] = $buyUserParent['user_id'];

                        $inArr['role_id'] = $buyUserParent['role_id'];
                        $inArr['role_name'] = $buyUserParent['role']['role_name'];
                        $inArr['level'] = 1;
                        $inArr['award_id'] = 1;
                        $inArr['type'] = 0;
                        $inArr['award_name'] = '会员推荐粉丝购物分奖';
                        $inArr['level_award_name'] = "下级【" . $buyUserInfo['user_id'] . "-" . userInfo($buyUserInfo['user_id']) . "】购买会员区产品,返".$member_amount_member."购物分";
                        $inArr['add_time'] = time();


                        if($member_amount_member>0) {
                            $res = $this->Model->insert($inArr);
                        }

                        $changedata['change_desc'] = '购物分返现...';
                        $changedata['change_type'] = 3;
                        if($member_amount_member>0){
                            $res = (new AccountModel())->change($changedata, $buyUserParent['user_id'], false);
                        }
                         //
                         /*
                         $useraccount = Db::table('users_account')->where('user_id',$piduserInfo['user_id'])->find();
                         $integral_money = sprintf("%01.2f",$useraccount['integral_money']+$dividend_amountyonghu);
                         $uparr['integral_money'] = $integral_money;
                         $useraccountres = Db::table('users_account')->where('user_id',$piduserInfo['user_id'])->update($uparr);
                         */
                        /*
                        $returnArr['dividend_amount'] += $member_amount_member;
                        $this->createLog($orderInfo, $buyUserParent, $member_amount_member, '会员推荐粉丝购物分奖', '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买会员区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $member_amount_member . '元' . '奖励', $dividend_goods_total, 'vip');
                        */

                        $buyUserParentFirst = $buyUserParents[$index + 1];

                        if($buyUserParentFirst['role_id'] == 2 && $dividend_amount_jingli > 0){
                                //


                                //级别：
                                $buyUserParentFirst = $buyUserParents[$index + 1] ?? [];
                                if (!empty($buyUserParentFirst) && $dividend_amount_jingli > 0) {
                                    $returnArr['dividend_amount'] += $dividend_amount_jingli;
                                    $this->createLog($orderInfo, $buyUserParentFirst, $dividend_amount_jingli, '会员推荐粉丝经理分销奖', '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买会员区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $dividend_amount_jingli . '元' . '奖励', $dividend_goods_total, $status);
                                }

                                //级别：
                                $buyUserParentSecond = $buyUserParents[$index + 2] ?? [];
                                if (!empty($buyUserParentSecond) && $dividend_amount_jingli > 0) {
                                    $dividend_amount_pingji = bcdiv($dividend_amount_jingli * $pingjimoney, 100, 2); //平级奖是固定的10%
                                    $returnArr['dividend_amount'] += $dividend_amount_pingji;
                                    $this->createLog($orderInfo, $buyUserParentSecond, $dividend_amount_pingji, '2会员推荐粉丝经理平级奖.', '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买会员区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $dividend_amount_pingji . '元' . '奖励', $dividend_goods_total, $status);
                                }
                        }


                        if($buyUserParentFirst['role_id'] != 2){






                            //$buyUserParentFirst = $buyUserParents[$index + 2] ?? [];
                            //if (!empty($buyUserParentFirst) && $dividend_amount_jicha > 0) {
                                //级别
                                //if($buyUserParentFirst['role_id'] == 1) {
                                    for ($i = 2; $i < count($buyUserParents); $i++) {
                                        $topBuyUserParent = $buyUserParents[$i] ?? [];
                                        if (!empty($topBuyUserParent) && $topBuyUserParent['role_id'] == 1) { //



                                                if(!empty($topBuyUserParent) && $dividend_amount_daili > 0){
                                                    $returnArr['dividend_amount'] += $dividend_amount_daili;
                                                    $this->createLog($orderInfo, $topBuyUserParent, $dividend_amount_daili, '会员推荐粉丝代理分销奖', '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买普通区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $dividend_amount_daili . '元' . '奖励', $dividend_goods_total, $status);
                                                }


                                                //
                                                $topBuyUserParentSecond = $buyUserParents[$i + 1] ?? [];

                                                if (!empty($topBuyUserParentSecond) && $dividend_amount_jingli > 0) {
                                                    $returnArr['dividend_amount'] += $dividend_amount_jicha;
                                                    $this->createLog($orderInfo, $topBuyUserParentSecond, $dividend_amount_jicha, '会员推荐粉丝经理级差奖', '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买普通区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $dividend_amount_jicha . '元' . '奖励', $dividend_goods_total, $status);
                                                }

                                                //
                                                $topBuyUserParentSecond = $buyUserParents[$i + 2] ?? [];
                                                if (!empty($topBuyUserParentSecond) && $dividend_amount_jingli > 0) {
                                                    $dividend_amount_pingji = bcdiv($dividend_amount_jingli * $pingjimoney, 100, 2); //平级奖是固定的10%
                                                    $returnArr['dividend_amount'] += $dividend_amount_pingji;
                                                    $this->createLog($orderInfo, $topBuyUserParentSecond, $dividend_amount_pingji, '会员推荐粉丝经理平级奖', '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买普通区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $dividend_amount_pingji . '元' . '奖励', $dividend_goods_total, $status);
                                                }

                                                break;
                                        }
                                    }
                                //}

                                /*
                                之前的
                                //级别：会员<代理<经理A，那么就经理A拿级差奖
                                if ($buyUserParentFirst['role_id'] == 2) {
                                    $returnArr['dividend_amount'] += $dividend_amount_jicha;
                                    $res = $this->createLog($orderInfo, $buyUserParentFirst, $dividend_amount_jicha, '6会员推荐粉丝经理分销奖', '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买普通区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $dividend_amount_jicha . '元' . '奖励', $dividend_goods_total, $status);
                                    //if (!$res) return false;

                                    //级别：会员<代理<经理A<经理B，那么就经理B拿平级奖
                                    $buyUserParentSecond = $buyUserParents[$index + 4] ?? [];
                                    if (!empty($buyUserParentSecond) && $buyUserParentSecond['role_id'] == 2 && $dividend_amount_jicha > 0) {
                                        $dividend_amount_pingji = bcdiv($dividend_amount_jicha * $pingjimoney, 100, 2); //平级奖是固定的10%
                                        $returnArr['dividend_amount'] += $dividend_amount_pingji;
                                        $res = $this->createLog($orderInfo, $buyUserParentSecond, $dividend_amount_pingji, '2会员推荐粉丝经理平级奖', '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买普通区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $dividend_amount_pingji . '元' . '奖励', $dividend_goods_total, $status);
                                        //if (!$res) return false;
                                    }
                                }
                                */

                            //}


                        }

                    }






                }
            }




        }

        return $returnArr;
    }

    /**
     * 寻找所有父级元素
     * @param $id
     * @param $ancestor
     * @return array
     */
    public function findParent($id, $ancestor)
    {
        static $parent = array();
        foreach ($ancestor as $v) {
            //从小到大 排列
            if ($v["user_id"] == $id) {
                $parent[] = $v;

                    findParent($v["pid"], $ancestor);

            }
        }
        return $parent;
    }

    public function getTopTree($categoryId, &$userArr = [])
    {
        $category = model('app\member\model\UsersModel')->find($categoryId)->toArray();
        if (!$category || $category['pid'] == 0) {
            return $userArr;
        } else {
            $userArr[] = $category;
            return $this->getTopTree($category['pid'], $userArr);
        }
    }


    /**
     * [createLog 保存分佣记录]
     * @param array $orderInfo [订单信息]
     * @param array $userInfo [用户信息]
     * @param float $dividend_amount [分佣金额]
     * @param string $award_name [分佣名]
     * @param string $level_award_name [分佣说明]
     * @param integer $status [分佣状态]
     * @param float $amount [参与分佣的金额]
     * @param integer $nowLevel [当前处理级别]
     * @return boolean                  [处理结果]
     */
    public function createLog($orderInfo = [], $userInfo = [], $dividend_amount = 0.00, $award_name = '', $level_award_name = '', $amount = 0.00, $status = 0, $nowLevel = 0, $md5log = '')
    {

        //设置地方释放扶持金

        $DividendInfo = settings('DividendInfo');
        $DividendSatus = settings('DividendSatus');
        $userModel = new \app\member\model\UsersModel();
        //根据注册时间最早的时间查3个下级用户
        $start_push_User = $userModel->where([
            ['pid', '=', $userInfo['user_id']],
            ['up_agent_time', '<>', ''],
        ])->order("up_agent_time asc")->limit($DividendInfo['rebate_push_num'])->select();


        $start_push_Usercount = $userModel->where([
            ['pid', '=', $userInfo['user_id']],
            ['up_agent_time', '<>', ''],
        ])->order("up_agent_time asc")->limit($DividendInfo['rebate_push_num'])->count();


        $manzugxIds = '';
        if ($start_push_Usercount > 0) {
            foreach ($start_push_User as $user){
                $manzugxIds .= $user['user_id'] . ',';
            }
            $pull_UserList = rtrim($manzugxIds,',');
        }


        $rebate_push_num = $userModel
            ->where([
                ['pid', '=', $userInfo['user_id']],
                ['role_id', '=', 2],
                ['user_id', 'in', $pull_UserList],
            ])
            ->count();


        $isrelease = 0;
        $AccountModels = new \app\member\model\AccountModel();
        if ($DividendSatus == 1) {
            if ($rebate_push_num >= $DividendInfo['rebate_push_num'] || $userInfo['isrelease'] == 1) {
                $isrelease = 1;
                $AccountModels->releaseSupport($userInfo['user_id']);
            }

        }

        //设置地方释放扶持金

        $DividendInfo = settings('DividendInfo');
        $dividend_bean = 0;
        $type = 0;
        if (strstr($award_name, "区域")) {
            $type = 1;
        }
        /*
        $rebate_push_num = $this->UsersModel
            ->where([
                ['pid', '=', $userInfo['user_id']],
                ['role_id', '=', 2],
                //                ['profit_pid', '<>', $userInfo['user_id']],
            ])
            ->count();
        */
        $AccountModels = new AccountModel();

        if ($DividendInfo['rebate_push_num'] > $rebate_push_num) {
            $total_dividend_amount = $dividend_amount;
            $dividend_amount = 0;
            if($status == 'vip' || $isrelease == 1){
                $dividend_amount = $total_dividend_amount;
                $dividend_bean = 0;
            }else{
                $dividend_amount = bcdiv($total_dividend_amount * $DividendInfo['balance_rebate'], 100, 2);
                $dividend_bean = bcdiv($total_dividend_amount * $DividendInfo['integral_rebate'], 100, 2);
            }

        } else {

            $AccountModels->releaseSupport($userInfo['user_id']);
        }



        $inArr['dividend_amount'] = $dividend_amount;
        $inArr['dividend_bean'] = $dividend_bean;
        $inArr['order_type'] = 'order';
        $inArr['status'] = 9;
        $inArr['order_id'] = $orderInfo['order_id'];
        $inArr['order_sn'] = $orderInfo['order_sn'];
        $inArr['buy_uid'] = $orderInfo['user_id'];
        $inArr['order_amount'] = $amount;
        $inArr['dividend_uid'] = $userInfo['user_id'];

        $inArr['role_id'] = $userInfo['role_id'];
        $inArr['role_name'] = $userInfo['role']['role_name'];
        $inArr['level'] = $nowLevel;
        $inArr['award_id'] = 1;
        $inArr['type'] = $type;
        $inArr['award_name'] = $award_name;
        $inArr['level_award_name'] = $level_award_name;
        $inArr['add_time'] = $inArr['update_time'] = time();
        if ($this->Model->where(['award_name' => $award_name, 'order_sn' => $inArr['order_sn'], 'dividend_uid' => $inArr['dividend_uid']])->find()) {
            return false;
        }

        $res = $this->Model->insert($inArr);

        if (!$res) return false;
        $AccountModel = new AccountModel();
        $changedata['change_desc'] = $inArr['level_award_name'];
        $changedata['change_type'] = 4;
        $changedata['by_id'] = $inArr['order_id'];
        $changedata['from_uid'] = $inArr['buy_uid'];
        $changedata[$status == 'vip' ? 'integral_money' : 'balance_money'] = $inArr['dividend_amount'];
        $changedata['bean_value'] = $inArr['dividend_bean'];
        $changedata['total_dividend'] = ($inArr['dividend_amount'] + $inArr['dividend_bean']);
        $changedata['md5log'] = $md5log;
        $AccountModel->change($changedata, $inArr['dividend_uid'], false);
        return true;
    }


      /**
     * 根据用户ID获取所有上级用户信息，以数组形式返回
     * @param $userId
     * @param array $users
     * @return array|mixed
     */
    public function getParentsByUserId($userId, &$users = [])
    {
        $userInfo = $this->UsersModel->info($userId);
        if (empty($userInfo)) {
            return $users;
        }
        $users[] = $userInfo;
        if ($userInfo['pid'] == 0) {
            array_shift($users); //去除本身数据
            return $users;
        }
        return $this->getParentsByUserId($userInfo['pid'], $users);
    }

}
